import React from "react";

import {
  View,
  Text,
  Image,
  FlatList,
  ActivityIndicator,
  TouchableOpacity,
} from "react-native";
import Api from "../utils/Api";
import { styles } from "./CustomFlatList.style";

const DEFAULT_SIZE = 20;
//分页
const PAGE_IS_LOADING = "pageIsLoading";
const PAGE_IS_NEXTPAGE = "pageIsNextPage";
const PAGE_IS_END = "pageIsEnd";
//页面
const IS_EMPTY = "isEmpty";
const IS_LOADDING = "isLoadding";
const IS_NET_ERROR = "isNetError";
const IS_LIST = "isList";

const EMPTY = require("./images/ic_empty.png");
const NETWORK_ERROR = require("./images/network-error.png");
function mergList(sourceList, nowList) {
  //原来sourceList，新的nowList
  if (sourceList) {
    nowList = sourceList.concat(nowList);
    return nowList;
  }
  return nowList;
}
function getRoundUpTotalPage(totalRows, pageSize) {
  return Math.ceil(totalRows / pageSize);
}
export default class CustomFlatList extends React.Component {
  state = {
    page: 1,
    isPage: false,
    pageStatus: IS_LOADDING,
    position: 0,
    refreshing: false,
  };
  async componentDidMount() {
    await this._getData();
  }
  _getData = async (data) => {
    try {
      let isPage = this.props.isPage || this.state.isPage;
      var req;
      if (isPage) {
        let position = this.state.position;
        if (data) {
          position = data.position;
        }
        req = {
          page: (data && data.page) || this.state.page,
          pageSize: this.props.pageSize || DEFAULT_SIZE,
          position: position,
          ...this.props.data,
        };
      } else {
        req = this.props.data;
      }
      const { api } = this.props;
      if (!api) return;
      // console.warn("请求数据====", req);
      let res = await Api.api({
        api: api,
        data: req,
        errorHandler: "alert",
      });
      // console.warn("返回的值============", res);
      this._dealRes(res);
    } catch (error) {
      if (error.message == "网络错误") {
        this.setState({ pageStatus: IS_NET_ERROR });
      }
      //这里是否可以判断是否网络错误呢？
    }
  };
  _dealRes = (res) => {
    if (!res) return;
    let isPage = this.props.isPage || this.state.isPage;
    if (isPage) {
      let pageSize = this.props.pageSize || DEFAULT_SIZE;
      if (res.totalRows == 0) {
        this.setState({ pageStatus: IS_EMPTY });
        return;
      }
      this.setState({
        totalRows: res.totalRows,
        queryList: mergList(this.state.queryList, res.list),
        pageStatus: IS_LIST,
      });
      let totalPage = getRoundUpTotalPage(res.totalRows, pageSize);
      if (totalPage > 1 && res.page != totalPage) {
        //说明有下一页
        this.setState({ pagingStatus: PAGE_IS_NEXTPAGE });
        return;
      }
      if (totalPage == 1) {
        this.setState({ pagingStatus: PAGE_IS_END });
        return;
      }
      if (totalPage == res.page) {
        this.setState({ pagingStatus: PAGE_IS_END });
        return;
      }
    }

    this.setState({ queryList: res, pageStatus: IS_LIST });
  };
  _onRefresherRefresh = async () => {
    //从新开始拉数据,数据从第一页开始拉取
    let data = {
      refreshing: true,
      page: 1,
      queryList: undefined,
      pageStatus: IS_LOADDING,
      position: 0,
    };
    this.setState(data);
    await this._getData(data);
    this.setState({ refreshing: false });
  };
  _loadMore = async () => {
    //此时加载分页中的下一页，并且与前一页进行合并
    let page = this.state.page;
    let pageSize = this.props.pageSize || DEFAULT_SIZE;
    page = page + 1;
    let position = this.state.position;
    position = position + pageSize;

    this.setState({
      page: page,
      pagingStatus: PAGE_IS_LOADING,
      position: position,
    });
    let data = {
      page: page,
      position: position,
    };
    await this._getData(data);
  };

  renderEmpty = () => {
    return (
      <TouchableOpacity
        style={styles.flatlistEmptyView}
        onPress={this._onRefresherRefresh}
      >
        <Image
          source={EMPTY}
          style={styles.flatlistEmptyImg}
          resizeMode="contain"
        />
        <Text style={styles.flatlistEmptyText}>暂无记录</Text>
      </TouchableOpacity>
    );
  };
  renderError = () => {
    //网络错误的时候显示，点击可以再次刷新
    return (
      <TouchableOpacity
        style={styles.flatlistEmptyView}
        onPress={this._onRefresherRefresh}
      >
        <Image
          source={NETWORK_ERROR}
          style={styles.flatlistEmptyImg}
          resizeMode="contain"
        />
        <Text style={styles.flatlistEmptyText}>网络出错啦！</Text>
      </TouchableOpacity>
    );
  };
  renderLoadding = () => {
    return (
      <View style={styles.flatListLoadding}>
        <ActivityIndicator size="large" />
        <Text style={styles.flatListLoadText}>加载中...</Text>
      </View>
    );
  };
  renderIsLoadAll = () => {
    return (
      <View style={styles.flatListLoadView}>
        <Text style={styles.flatListLoadText}>已加载全部</Text>
      </View>
    );
  };
  renderLoadMore = () => {
    return (
      <TouchableOpacity
        onPress={this._loadMore}
        style={styles.flatListLoadView}
      >
        <Text style={styles.flatListLoadText}>加载更多</Text>
      </TouchableOpacity>
    );
  };
  renderLoaddingPage = () => {
    return (
      <View style={styles.flatListLoadView}>
        <Text style={styles.flatListLoadText}>加载中...</Text>
      </View>
    );
  };

  renderFooter = () => {
    //区分 分页 和 不分页
    //不分页：显示 已加载全部  不可点击     分页=>判断是否有下一页，如果totalRows/pageSize >1 则说明有下页： 加载更多   加载中...    已加载全部\
    const { pagingStatus } = this.state;
    let isPage = this.props.isPage || this.state.isPage;
    if (!isPage) {
      return this.renderIsLoadAll();
    }
    switch (pagingStatus) {
      case PAGE_IS_NEXTPAGE:
        return this.renderLoadMore();

      case PAGE_IS_LOADING:
        return this.renderLoaddingPage();

      case PAGE_IS_END:
        return this.renderIsLoadAll();
      default:
        return null;
    }
  };
  _itemSeparatorComponent = () => {
    return <View style={styles.lineView} />;
  };
  _onEndReached = () => {
    const { pagingStatus } = this.state;
    if (pagingStatus == PAGE_IS_NEXTPAGE) {
      this._loadMore();
    }
  };
  _keyExtractor = (item, index) => "key" + index;
  renderList = () => {
    const { renderItem, style, itemSeparatorComponent } = this.props;
    const { queryList, refreshing } = this.state;
    return (
      <FlatList
        ref={(flatList) => (this._flatList = flatList)}
        onRefresh={this._onRefresherRefresh}
        data={queryList}
        ListEmptyComponent={this.renderEmpty()}
        refreshing={refreshing}
        renderItem={renderItem}
        ItemSeparatorComponent={
          itemSeparatorComponent || this._itemSeparatorComponent
        }
        ListFooterComponent={this.renderFooter}
        keyExtractor={this._keyExtractor}
        onEndReached={this._onEndReached}
        onEndReachedThreshold={0.2}
      />
    );
  };
  render() {
    const { pageStatus } = this.state;
    return (
      <View>
        {pageStatus == IS_EMPTY && this.renderEmpty()}
        {pageStatus == IS_LIST && this.renderList()}
        {pageStatus == IS_LOADDING && this.renderLoadding()}
        {pageStatus == IS_NET_ERROR && this.renderError()}
      </View>
    );
  }
}
